<!DOCTYPE html>
<html>

<head>
    <title>一元线性回归模型算法</title>
    <meta charset="utf-8">
    <meta name="viewport"
        content="width=device-width,target-densitydpi=device-dpi,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="format-detection" content="telephone=no" />
    <meta name="format-detection" content="email=no" />
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Expires" content="0" />
    <style>
        * {
            font-size: 30px;
        }

        textarea {
            display: block;
            font-size: 24px;
            width: 500px;
            margin: 20px 0;
        }

        #btn {
            margin: 20px 0;
            padding: 20px 40px;
            border-radius: 5px;
            background-color: #333;
            color: #fff;
            cursor: pointer;
            display: inline-block;
            user-select: none;
        }
    </style>
</head>
<div class="title">输入X: (格式：num,num,num)</div>
<textarea id="xInput"></textarea>
<div class="title">输入Y: </div>
<textarea id="yInput"></textarea>
<div id="btn" onclick="countAB()">计算</div>
<div id="result">a=0,b=0</div>

<body>
</body>

<script>
    var xInput = document.getElementById("xInput");
    var yInput = document.getElementById("yInput");
    var btn = document.getElementById("btn");
    var result = document.getElementById("result");

    /*
     计算a,b的值
    **/
    function countAB() {
        var x = xInput.value;
        var y = yInput.value;
        x = x.split(",");
        y = y.split(",");

        var sum_x2 = 0.0;
        var sum_y = 0.0;
        var sum_x = 0.0;
        var sum_xy = 0.0;

        var a = 0, b = 0;

        if (x.length != y.length) {
            result.innerHTML = "数组格式不对，或者x,y长度不同";
        }
        else {
            var num = x.length;
            for (var i = 0; i < num; ++i) {
                sum_x2 += Number(x[i]) * Number(x[i]);
                sum_y += Number(y[i]);
                sum_x += Number(x[i]);
                sum_xy += Number(x[i]) * Number(y[i]);
            }

            a = (num * sum_xy - sum_x * sum_y) / (num * sum_x2 - sum_x * sum_x);
            b = (sum_x2 * sum_y - sum_x * sum_xy) / (num * sum_x2 - sum_x * sum_x);

            result.innerHTML = "a="+a+",b="+b;
        }
    }
</script>

</html>